package com.hotelManager.www.dao;

import com.hotelManager.www.po.RoomType;
import com.hotelManager.www.util.JDBCUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class RoomTypeDao {
    /**
     * 创建房型
     */
    public boolean create(Connection conn, RoomType roomType) throws SQLException {
        String sql = "INSERT INTO room_type (shop_id, type_name, price, stock, bed_type) VALUES (?, ?, ?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setInt(1, roomType.getShopId());
            pstmt.setString(2, roomType.getTypeName());
            pstmt.setBigDecimal(3, roomType.getPrice());
            pstmt.setInt(4, roomType.getStock());
            pstmt.setString(5, roomType.getBedType());
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        roomType.setId(generatedKeys.getInt(1));
                        return true;
                    }
                }
            }
            return false;
        }
    }

    /**
     * 根据ID获取房型
     */
    public RoomType findById(Integer id) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "SELECT * FROM room_type WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            if (rs.next()) {
                return extractRoomTypeFromResultSet(rs);
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (rs != null) rs.close();
            if (ps != null) ps.close();
            if (conn != null) conn.close();
        }
    }

    /**
     * 根据店铺ID获取房型列表
     */
    public List<RoomType> findByShopId(Connection conn, Integer shopId) throws SQLException {
        String sql = "SELECT id, shop_id, type_name, price, stock, bed_type FROM room_type WHERE shop_id = ?";
        System.out.println("[RoomTypeDao] SQL: " + sql + ", shopId=" + shopId);
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, shopId);
            try (ResultSet rs = ps.executeQuery()) {
                List<RoomType> roomTypes = new ArrayList<>();
                while (rs.next()) {
                    RoomType roomType = new RoomType();
                    roomType.setId(rs.getInt("id"));
                    roomType.setShopId(rs.getInt("shop_id"));
                    roomType.setTypeName(rs.getString("type_name"));
                    roomType.setPrice(rs.getBigDecimal("price"));
                    roomType.setStock(rs.getInt("stock"));
                    roomType.setBedType(rs.getString("bed_type"));
                    roomTypes.add(roomType);
                }
                System.out.println("[RoomTypeDao] 查询到房型数量: " + roomTypes.size());
                return roomTypes;
            }
        } catch (Exception e) {
            System.out.println("[RoomTypeDao] 查询房型异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 更新房型信息
     */
    public boolean update(Connection conn, RoomType roomType) throws SQLException {
        String sql = "UPDATE room_type SET type_name = ?, price = ?, stock = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, roomType.getTypeName());
            pstmt.setBigDecimal(2, roomType.getPrice());
            pstmt.setInt(3, roomType.getStock());
            pstmt.setInt(4, roomType.getId());
            return pstmt.executeUpdate() > 0;
        }
    }

    /**
     * 删除房型
     */
    public boolean delete(Connection conn, Integer id) throws SQLException {

        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "DELETE FROM room_type WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            return ps.executeUpdate() > 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (ps != null) ps.close();
            if (conn != null) conn.close();
        }
    }

    /**
     * 查找所有房型
     */
    public List<RoomType> findAll() throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "SELECT * FROM room_type";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            List<RoomType> roomTypes = new ArrayList<>();
            while (rs.next()) {
                roomTypes.add(extractRoomTypeFromResultSet(rs));
            }
            return roomTypes;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (rs != null) rs.close();
            if (ps != null) ps.close();
            if (conn != null) conn.close();
        }
    }

    /**
     * 更新房型库存
     */
    public void updateStock(Integer roomTypeId, int change) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "UPDATE room_type SET stock = stock + ? WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, change);
            ps.setInt(2, roomTypeId);
            ps.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (ps != null) ps.close();
            if (conn != null) conn.close();
        }
    }

    /**
     * 从ResultSet中提取RoomType对象
     */
    private RoomType mapResultSetToRoomType(ResultSet rs) throws SQLException {
        RoomType roomType = new RoomType();
        roomType.setId(rs.getInt("id"));
        roomType.setShopId(rs.getInt("shop_id"));
        roomType.setTypeName(rs.getString("type_name"));
        roomType.setPrice(rs.getBigDecimal("price"));
        roomType.setStock(rs.getInt("stock"));
        return roomType;
    }

    /**
     * 从ResultSet中提取RoomType对象（别名方法）
     */
    private RoomType extractRoomTypeFromResultSet(ResultSet rs) throws SQLException {
        RoomType roomType = new RoomType();
        roomType.setId(rs.getInt("id"));
        roomType.setShopId(rs.getInt("shop_id"));
        roomType.setTypeName(rs.getString("type_name"));
        roomType.setPrice(rs.getBigDecimal("price"));
        roomType.setStock(rs.getInt("stock"));
        roomType.setBedType(rs.getString("bed_type"));
        return roomType;
    }
}
